﻿using K9Nano.Updater.Utils;

namespace K9Nano.Updater.Pipes;

public class UpdatePipeManger : IUpdatePipeManger
{
    private readonly IReadOnlyList<IUpdatePipe> _pipes;

    public static readonly IReadOnlyList<IUpdatePipe> DefaultPipes = [
            new CheckVersionPipe(),
            new DownloadPipe(),
            new CheckSumPipe(),
            new BackupPipe(),
            new PreInstallPipe(),
            new InstallPipe(),
            new PostInstallPipe(),
            new RollbackPipe()
        ];

    public UpdatePipeManger() : this(DefaultPipes)
    {
    }

    public UpdatePipeManger(IReadOnlyList<IUpdatePipe> pipes)
    {
        _pipes = pipes;
    }

    public virtual async Task InvokeAsync(UpdateContext context, CancellationToken cancellation)
    {
        context.StepCount = _pipes.Count;
        if (cancellation.IsCancellationRequested)
        {
            context.Success = false;
            context.Terminated = true;
            context.LogWarning("已经取消更新");
            return;
        }
        try
        {
            for (var i = 0; i < _pipes.Count; i++)
            {
                var pipe = _pipes[i];
                context.CurrentPipe = pipe;
                context.CurrentStep = i;
                await pipe.InvokeAsync(context, cancellation);

                if (cancellation.IsCancellationRequested)
                {
                    context.Success = false;
                    context.Terminated = true;
                    context.LogWarning("已经取消更新");
                    return;
                }
#if DEBUG
                await Task.Delay(1000);
#endif
            }

            if (context.Success)
            {
                context.ReportSuccess();
                context.CurrentPipe = null;
            }
        }
        catch (TaskCanceledException)
        {
            context.Success = false;
            context.Terminated = true;
            context.LogWarning("已经取消更新");
        }
        catch (Exception ex)
        {
            context.LogError(ex, "更新失败");
            context.Terminated = true;
            context.Success = false;
        }

        Clean(context);
    }

    protected virtual void Clean(UpdateContext context)
    {
        context.LogInformation("清理临时文件");
        try
        {
            foreach (var path in context.TempDirectories)
            {
                PathUtils.ForceDeleteDirectory(path);
            }
        }
        catch (Exception ex)
        {
            context.LogError(ex, "清理临时文件失败");
        }
    }
}